package qsbk.app.play.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

import qsbk.app.play.common.TopicPool;
import qsbk.app.play.websocket.GameWebSocket;

public class Room {
	
	private int roomId;
	
	private String performTopic;
	private int performUser = 0;
	
	private List<GameWebSocket> websockets;
	private List<String> userIds;

	// 题目池
	private TopicPool topicPool;
	private Gson gson;
	
	public Room() {
		topicPool = new TopicPool();
		gson = new Gson();
	}
	
	public void setWebsockets(List<GameWebSocket> websockets) {
		this.websockets = websockets;
		
		userIds = new ArrayList<>(websockets.size());
		for (GameWebSocket websocket : websockets) {
			userIds.add(websocket.getUid());
		}
	}

	public String getNextPerform() {
        if (performUser < userIds.size()) {
			return userIds.get(performUser ++);
        } else {
        	return null;
        }
	}

	public List<String> getTopics() {
		return topicPool.getTopics();
	}

	public void close() {
		topicPool.reset();
		topicPool = null;
		gson = null;
		performTopic = null;
		userIds.clear();
		userIds = null;
		
		for (GameWebSocket item : websockets) {
			try {
				if (item != null) {
					item.getSession().close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
		}
		websockets.clear();
		websockets = null;
	}

	public List<String> generateGuessWords(String topic) {
		return topicPool.generateGuessWords(topic);
	}
	
	public void broadcast(Object obj) {
		broadcast(gson.toJson(obj));
	}
	
	public void broadcast(String message) {
		// 群发消息
		for (GameWebSocket item : websockets) {
			try {
				if (item != null) {
					item.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
		}
	}

	public void onClose(GameWebSocket websocket) {
		int index = websockets.indexOf(websocket);
		if (index != -1) {
			websockets.set(index, null);// 设置已销毁
		}
	}

	public void onOpen(GameWebSocket websocket) {
		int index = userIds.indexOf(websocket.getUid());
		if (index != -1) {
			websockets.set(index, websocket);// 设置已重连
		}
	}

	public void setRoomId(int roomId) {
		this.roomId = roomId;
	}
	
	public int getRoomId() {
		return roomId;
	}

	public void setPerformTopic(String topic) {
		this.performTopic = topic;
	}
	
	public String getPerformTopic() {
		return performTopic;
	}

	public boolean hasUser(String uid) {
		return userIds.contains(uid);
	}

}
